# logic/button_handlers.py

from logic.history_data import update_history
from logic.evaluator import safe_eval
import math

def on_button_click(char, expression_state, result_state, update_display):
    """
    处理数字和运算符按钮点击
    """
    expr = expression_state['expression']
    just_eval = expression_state['just_evaluated']
    operators = set('+-*/^')

    if char in operators:
        prev = result_state['result'] or '0'
        if just_eval:
            expr = prev + ('**' if char == '^' else char)
        else:
            expr += ('**' if char == '^' else char)
        expression_state['just_evaluated'] = False
        expression_state['expression'] = expr
        update_display()
        return

    # 普通字符（数字、小数点、括号、^）
    if just_eval:
        expr = ('**' if char == '^' else char)
    else:
        expr += ('**' if char == '^' else char)

    expression_state['expression'] = expr
    expression_state['just_evaluated'] = False
    update_display()


def clear_expression(expression_state, result_state, update_display):
    """
    清空表达式和结果
    """
    expression_state['expression'] = ""
    expression_state['just_evaluated'] = False
    result_state['result'] = ""
    update_display()


def backspace(expression_state, update_display):
    """
    删除最后一个字符（如果是 ** 则一次删除两字符）
    """
    expr = expression_state['expression']
    if expr.endswith('**'):
        expr = expr[:-2]
    else:
        expr = expr[:-1]
    expression_state['expression'] = expr
    update_display()


def evaluate_expression(expression_state, result_state, update_display):
    """
    计算当前表达式并格式化结果
    """
    expr = expression_state['expression']
    raw = safe_eval(expr)
    try:
        val = float(raw)
        if val.is_integer():
            formatted = str(int(val))
        else:
            formatted = f"{val:.6f}".rstrip('0').rstrip('.')
    except:
        formatted = "你真是个⑨|ू･ω･` )"
    result_state['result'] = formatted
    update_history(f"{expr.replace('**','^')} = {formatted}")
    expression_state['expression'] = formatted
    expression_state['just_evaluated'] = True
    update_display()


def insert_factorial(expression_state, update_display):
    expression_state['expression'] += "factorial("
    update_display()


def insert_cirno(result_state, update_display):
    result_state['result'] = "バカバカ"
    update_display()


def insert_root(expression_state, update_display):
    expression_state['expression'] += "root("
    update_display()


def insert_log(expression_state, update_display):
    expression_state['expression'] += "log("
    update_display()


def handle_function(func_name, expression_state, result_state, update_display):
    """
    高级函数（x²、sin、cos…）仅构造表达式，不立即计算
    """
    func_map = {
        'square': lambda x: f"({x})**2",
        'cube':   lambda x: f"({x})**3",
        'sqrt':   lambda x: f"sqrt({x})",
        'abs':    lambda x: f"abs({x})",
        'exp':    lambda x: f"exp({x})",
        'sin':    lambda x: f"sin({x})",
        'cos':    lambda x: f"cos({x})",
        'tan':    lambda x: f"tan({x})",
        'π':      lambda x: str(math.pi),
    }
    expr = expression_state['expression']
    if expression_state['just_evaluated']:
        expr = result_state['result']
    if not expr or func_name not in func_map:
        return
    expression_state['expression'] = func_map[func_name](expr.replace('^','**'))
    expression_state['just_evaluated'] = False
    update_display()
